package com.zdkj.subway.st.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.annotation.Inner;
import com.zdkj.subway.st.entity.StTkFinancialReconciliation;
import com.zdkj.subway.st.service.StTkFinancialReconciliationService;
import com.zdkj.subway.st.util.DateUtilsSt;
import com.zdkj.subway.st.util.LocalDateConverter;
import com.zdkj.subway.st.util.LocalDateTimeConverter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.List;


/**
 * 财务对账模块
 *
 * @author chenbo
 * @date 2020-06-10 10:21:02
 */
@RestController
@AllArgsConstructor
@RequestMapping("/sttkfinancialreconciliation")
@Api(value = "sttkfinancialreconciliation", tags = "财务对账模块管理")
public class StTkFinancialReconciliationController {

    private final StTkFinancialReconciliationService stTkFinancialReconciliationService;

    /**
     * 分页查询
     *
     * @param page                        分页对象
     * @param stTkFinancialReconciliation 财务对账模块
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getStTkFinancialReconciliationPage(Page page, StTkFinancialReconciliation stTkFinancialReconciliation) {
        LocalDate startTime = null;
        LocalDate endTime = null;
        if (stTkFinancialReconciliation.getAccountStartTime() != null) {
            startTime = stTkFinancialReconciliation.getAccountStartTime();
            stTkFinancialReconciliation.setAccountStartTime(null);

        }
        if (stTkFinancialReconciliation.getAccountEndTime() != null) {
            endTime = stTkFinancialReconciliation.getAccountEndTime();
            stTkFinancialReconciliation.setAccountEndTime(null);

        }
        return R.ok(stTkFinancialReconciliationService.page(page, Wrappers.query(stTkFinancialReconciliation)
                .orderByDesc("account_start_time")
                .lambda()
                .ge(startTime == null ? false : true, StTkFinancialReconciliation::getAccountStartTime, startTime)
                .le(endTime == null ? false : true, StTkFinancialReconciliation::getAccountEndTime, endTime)));
    }


    /**
     * 导出
     *
     * @param page                        分页对象
     * @param stTkFinancialReconciliation 财务对账
     * @return
     */
    @ApiOperation(value = "财务对账导出", notes = "财务对账导出")
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('st_sttkfinancialreconciliation_export')")
    public void getExport(Page page, StTkFinancialReconciliation stTkFinancialReconciliation, HttpServletResponse response) throws IOException {

        LocalDate startTime = null;
        LocalDate endTime = null;
        if (stTkFinancialReconciliation.getAccountStartTime() != null) {
            startTime = stTkFinancialReconciliation.getAccountStartTime();
            stTkFinancialReconciliation.setAccountStartTime(null);

        }
        if (stTkFinancialReconciliation.getAccountEndTime() != null) {
            endTime = stTkFinancialReconciliation.getAccountEndTime();
            stTkFinancialReconciliation.setAccountEndTime(null);

        }
        IPage pageSt = stTkFinancialReconciliationService.page(page, Wrappers.query(stTkFinancialReconciliation)
                .lambda()
                .ge(startTime == null ? false : true, StTkFinancialReconciliation::getAccountStartTime, startTime)
                .le(endTime == null ? false : true, StTkFinancialReconciliation::getAccountEndTime, endTime));
        // 写法1
        String fileName = URLEncoder.encode("财务对账", "UTF-8");
        //"C:\\Users\\Administrator\\Desktop\\" + "simpleWrite" + System.currentTimeMillis() + ".xlsx";
        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + DateUtilsSt.getDatetimeNowFormatter() + ".xlsx");
        EasyExcel.write(response.getOutputStream(), StTkFinancialReconciliation.class).registerConverter(new LocalDateTimeConverter())
                .registerConverter(new LocalDateConverter()).sheet("财务对账").doWrite(pageSt.getRecords());
    }

    /**
     * 通过id查询财务对账模块
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(stTkFinancialReconciliationService.getById(id));
    }

    /**
     * 新增财务对账模块
     *
     * @param stTkFinancialReconciliation 财务对账模块
     * @return R
     */
    @ApiOperation(value = "新增财务对账模块", notes = "新增财务对账模块")
    @SysLog("新增财务对账模块")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('st_sttkfinancialreconciliation_add')")
    public R save(@RequestBody StTkFinancialReconciliation stTkFinancialReconciliation) {
        return R.ok(stTkFinancialReconciliationService.save(stTkFinancialReconciliation));
    }

    /**
     * 修改财务对账模块
     *
     * @param stTkFinancialReconciliation 财务对账模块
     * @return R
     */
    @ApiOperation(value = "修改财务对账模块", notes = "修改财务对账模块")
    @SysLog("修改财务对账模块")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('st_sttkfinancialreconciliation_edit')")
    public R updateById(@RequestBody StTkFinancialReconciliation stTkFinancialReconciliation) {
        return R.ok(stTkFinancialReconciliationService.updateById(stTkFinancialReconciliation));
    }

    /**
     * 通过id删除财务对账模块
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除财务对账模块", notes = "通过id删除财务对账模块")
    @SysLog("通过id删除财务对账模块")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('st_sttkfinancialreconciliation_del')")
    public R removeById(@PathVariable Integer id) {
        return R.ok(stTkFinancialReconciliationService.removeById(id));
    }

    /**
     * 按月统计公务票金额(类型)
     *
     * @return R
     */
    @ApiOperation(value = "按月统计公务票金额(类型)", notes = "按月统计公务票金额(类型)")
    @Inner
    @PostMapping("/countMoney")
    public R countMoney() {
        String preMonth = DateUtil.lastMonth().toDateStr();
        List<StTkFinancialReconciliation> listCalc =
                stTkFinancialReconciliationService.calc(preMonth);
        listCalc.forEach(calc -> {
            //计算出来先检查之前库有没有，有了就更新，没有就加上
            StTkFinancialReconciliation db = stTkFinancialReconciliationService.getOne(
                    Wrappers.<StTkFinancialReconciliation>query().lambda()
                            .like(StTkFinancialReconciliation::getAccountStartTime, calc.getAccountStartTime())
                            .eq(StTkFinancialReconciliation::getHandleType, calc.getHandleType()));
            if (null != db) {
                //不为空就给ID用来更新
                calc.setId(db.getId());
            }
        });
        return R.ok(stTkFinancialReconciliationService.saveOrUpdateBatch(listCalc));

    }
}
